package com.zyc.mark.WaterMark;


import com.zyc.mark.Enum.StringEnum;
import com.zyc.mark.util.FileUtil;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author 白芷
 * @Date 2017/03/12
 * @use 利用Java代码给图片加水印
 */
@Slf4j
public class WaterMarkFactory {
    /**
     * @param srcImgPath 源图片路径
     * @param tarImgPath 保存的图片路径
     * @param sWaterMarkFile 水印内容文件
     */
    public void addWaterMark(String srcImgPath, String tarImgPath, String sWaterMarkFile) {
        try {
            // 读取原图片信息
            //得到文件
            File srcImgFile = new File(srcImgPath);
            //文件转化为图片
            Image srcImg = ImageIO.read(srcImgFile);
            //得到文件
            File waterMarkFile = new File(sWaterMarkFile);
            //文件转化为图片
            Image waterMarkImg = ImageIO.read(waterMarkFile);
            //文件转化为图片
            // com.itextpdf.text.Image waterMarkImg = com.itextpdf.text.Image.getInstance(waterMarkFile.getAbsolutePath());
            //获取图片的宽
            int srcImgWidth = srcImg.getWidth(null);
            //获取图片的高
            int srcImgHeight = srcImg.getHeight(null);
            // 加水印
            BufferedImage bufImg = new BufferedImage(srcImgWidth, srcImgHeight, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bufImg.createGraphics();
            g.drawImage(srcImg, 0, 0, srcImgWidth, srcImgHeight, null);
            //设置水印的坐标
            int x = 0;  
            int y = 0;  
            // waterMarkImg.setRotationDegrees(-45);
            //画出水印
            g.drawImage(waterMarkImg, 0, 0, waterMarkImg.getWidth(null), waterMarkImg.getHeight(null), null);
            g.dispose();  
            // 输出图片  
            FileOutputStream outImgStream = new FileOutputStream(tarImgPath);
            log.info(FileUtil.getSuffix(srcImgPath) + " " + tarImgPath);
            ImageIO.write(bufImg,FileUtil.getSuffix(srcImgPath) , new File(tarImgPath));
            log.info("添加水印完成  ： " + srcImgPath);
            outImgStream.flush();
            outImgStream.close();  

        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
    
    public void createWaterMark(String tarImgPath, String waterMarkContent,Color markContentColor,Font font) {
        try {
            // 根据文本长度决定水印大小
            BufferedImage tempImgForSize = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
            Graphics2D waterMarkGraphics = tempImgForSize.createGraphics();
            waterMarkGraphics.setFont(font);
            int srcImgHeigth = 3 * getWatermarkheigth(waterMarkContent, waterMarkGraphics);
            int srcImgWidth = 100 + getWatermarkLength(waterMarkContent, waterMarkGraphics);
            waterMarkGraphics.dispose();
            BufferedImage bufImg = 
            	new BufferedImage(srcImgWidth, srcImgHeigth, BufferedImage.TYPE_INT_RGB);
            waterMarkGraphics = bufImg.createGraphics();
            bufImg = waterMarkGraphics.getDeviceConfiguration()
            		.createCompatibleImage(srcImgWidth, srcImgHeigth, Transparency.TRANSLUCENT);  
            waterMarkGraphics.dispose();
            waterMarkGraphics = bufImg.createGraphics();
            //根据图片的背景设置水印颜色
            waterMarkGraphics.setColor(markContentColor);
            //设置字体
            waterMarkGraphics.setFont(font);
            //设置水印的坐标
            int x = 50;
            int y = srcImgHeigth / 2;
            //System.out.println("x="+ x +" y="+ y + " srcImgWidth=" + srcImgWidth);
            //画出水印
            waterMarkGraphics.drawString(waterMarkContent, x, y);
            waterMarkGraphics.dispose();
            //缩放
            //设置缩放目标图片模板
            Image tempImageWaterMark = bufImg.getScaledInstance(srcImgWidth/2, srcImgHeigth/2, BufferedImage.SCALE_SMOOTH);
            //获取缩放比例
            double wr = 0.5;   double hr= 0.5;
            //hr=h*1.0 / bufImg.getHeight();
            AffineTransformOp ato = new AffineTransformOp(AffineTransform.getScaleInstance(wr, hr), null);
            tempImageWaterMark = ato.filter(bufImg, null);
            
            // 输出图片
            String tarImgParentPath = tarImgPath
            	.substring(0, tarImgPath.lastIndexOf(StringEnum.BACK_SLANT.getParam()));
            if(! new File(tarImgParentPath).exists()) {
                boolean mkdirs = new File(tarImgParentPath).mkdirs();
            }
            try (FileOutputStream outImgStream = new FileOutputStream(tarImgPath)){
                log.info(tarImgPath);
                ImageIO.write((BufferedImage)tempImageWaterMark, "png", new File(tarImgPath));
                log.info("生成水印完成:" + tarImgPath);
                outImgStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
    }
    public int getWatermarkLength(String waterMarkContent, Graphics2D g) {  
        return g.getFontMetrics(g.getFont())
        		.charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());  
    }  
    public int getWatermarkheigth(String waterMarkContent, Graphics2D g) {  
        return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0,1);  
    }
    public static void main(String[] args) {
        System.out.println(new File(".").getAbsoluteFile());
        System.out.println(new File("./src/main/resources").getAbsoluteFile());
        System.out.println(new File("./src/main/resources").getAbsoluteFile());
        //水印字体
        Font font = new Font("微软雅黑", Font.PLAIN, 35);
        //源图片地址
        String srcImgPath="D:/s.jpg";
        //待存储的地址
        // WaterMarkFactory.class.getClassLoader()
        String tarImgPath="./src/main/resources/pic/waterMark/waterMark.jpg";
        //待存储的地址
        String tarImgPath2="D:/t.jpg";
        //水印内容
        String waterMarkContent="zyc";
        Color color=new Color(200,200,200,80);
        //水印图片色彩以及透明度
        //new WaterMarkFactory().addWaterMark(srcImgPath, tarImgPath2, waterMarkContent, color,font);
        new WaterMarkFactory().createWaterMark(tarImgPath, waterMarkContent, color,font);
    }
}